<template>
    <el-dialog v-model="dialogVisible" title="批量导入表计" width="900px" destroy-on-close draggable @close="handleClose">
        <div class="batch-import-container">
            <!-- 导入设置 -->
            <div class="import-settings">
                <h4>导入设置</h4>
                <el-form :model="importSettings" label-width="120px" class="settings-form">
                    <div class="form-item-row">
                        <el-form-item label="默认引擎">
                            <el-select v-model="importSettings.engine_id" placeholder="请选择引擎" style="width: 200px;">
                                <el-option v-for="engine in engineList" :key="engine.value" :label="engine.label"
                                    :value="engine.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="默认制造商">
                            <el-input v-model="importSettings.manufacturer" placeholder="请输入制造商"
                                style="width: 200px;"></el-input>
                        </el-form-item>
                        <el-form-item label="安装日期">
                            <el-date-picker v-model="importSettings.installation_date" type="date" placeholder="选择日期"
                                style="width: 200px;" />
                        </el-form-item>
                    </div>
                </el-form>
            </div>

            <!-- 文件上传 -->
            <div class="file-upload-section">
                <h4>上传Excel文件</h4>
                <el-upload ref="uploadRef" class="upload-demo" drag :auto-upload="false" :on-change="handleFileChange"
                    :before-remove="beforeRemove" :limit="1" accept=".xlsx,.xls">
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        将Excel文件拖到此处，或<em>点击上传</em>
                    </div>
                    <div class="el-upload__tip">
                        只能上传xlsx/xls文件，且不超过2MB
                    </div>
                </el-upload>

                <!-- Excel格式说明 -->
                <div class="format-help">
                    <h5>Excel格式说明：</h5>
                    <el-table :data="excelFormatData" size="small" style="margin-top: 10px;">
                        <el-table-column prop="column" label="Excel列" width="100" />
                        <el-table-column prop="name" label="字段名称" width="120" />
                        <el-table-column prop="description" label="说明" />
                        <el-table-column prop="example" label="示例" width="100" />
                    </el-table>
                </div>
            </div>

            <!-- 数据预览 -->
            <div v-if="previewData.length > 0" class="preview-section">
                <h4>数据预览 (前10条)</h4>
                <el-table :data="previewData.slice(0, 10)" style="width: 100%" max-height="300">
                    <el-table-column prop="type" label="表计类型" width="80" />
                    <el-table-column prop="meter_id" label="表号" width="120" />
                    <el-table-column prop="installation_location" label="安装位置" width="120" />
                    <el-table-column prop="meter_code" label="表计编码" width="120" />
                    <el-table-column prop="specification" label="规格" width="100" />
                    <el-table-column prop="parent_meter_id" label="上级表号" width="100" />
                    <el-table-column prop="area_name" label="区域" width="100" />
                    <el-table-column prop="engine_type" label="引擎类型" width="100" />
                </el-table>
                <div class="preview-info">
                    <span>共 {{ previewData.length }} 条数据</span>
                    <span style="margin-left: 20px;">
                        水表: {{previewData.filter(item => item.type === '水表').length}} 个
                    </span>
                    <span style="margin-left: 20px;">
                        电表: {{previewData.filter(item => item.type === '电表').length}} 个
                    </span>
                </div>
            </div>

            <!-- 导入进度 -->
            <div v-if="importProgress.visible" class="import-progress">
                <h4>导入进度</h4>
                <el-progress :percentage="importProgress.percentage" :status="importProgress.status" :stroke-width="20"
                    text-inside />
                <div class="progress-text">
                    {{ importProgress.text }}
                </div>
            </div>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="startImport"
                    :disabled="previewData.length === 0 || importProgress.visible" :loading="importProgress.visible">
                    开始导入
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import * as XLSX from 'xlsx';
import dayjs from 'dayjs';
import { getMeterInfoApi, addMeterApi } from '@/api/meter';
import { useCompanyStore } from '@/stores/company';
import { useAreaStore } from '@/stores/area';
import { engineList } from '@/constants';

// Props
const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    }
});

// Emits
const emit = defineEmits(['update:visible', 'success']);

// Stores
const companyStore = useCompanyStore();
const areaStore = useAreaStore();

// 响应式数据
const dialogVisible = ref(false);
const uploadRef = ref(null);
const previewData = ref([]);
const importSettings = ref({
    engine_id: 9, // 默认诺特
    manufacturer: '诺特',
    installation_date: new Date()
});
const importProgress = ref({
    visible: false,
    percentage: 0,
    status: '',
    text: ''
});

// Excel格式说明数据
const excelFormatData = [
    { column: 'A', name: '表计类型', description: '水表/电表', example: '水表' },
    { column: 'B', name: '表号', description: '表计编号', example: '12345' },
    { column: 'C', name: '安装位置', description: '安装地点', example: '1楼' },
    { column: 'D', name: '表计编码', description: '表计代码', example: 'WM001' },
    { column: 'F', name: '规格', description: '表计规格', example: 'DN20' },
    { column: 'E', name: '信驰表号', description: '信驰机器人表号', example: '67890' },
    { column: 'I', name: '上级表号', description: '父表编号', example: '54321' },
    { column: 'J', name: '区域', description: '所属区域', example: '办公区' }
];

// 监听visible变化
watch(() => props.visible, (newVal) => {
    dialogVisible.value = newVal;
});

watch(dialogVisible, (newVal) => {
    if (!newVal) {
        emit('update:visible', false);
    }
});

// 直接获取所有表计的函数（不通过Store，避免类型限制）
const getAllMeters = async () => {
    try {
        const response = await getMeterInfoApi({
            company_id: companyStore.currentCompany.id
            // 不传type参数，获取所有类型的表计
        });
        if (response.code !== 200) {
            throw new Error(response.message || '获取表计列表失败');
        }
        return response.data || [];
    } catch (error) {
        console.error('获取表计列表失败:', error);
        return [];
    }
};

// 根据表号获取表计ID
const getMeterIdByMeterId = (meterList, meter_id) => {
    const meter = meterList.find(m => m.meter_id === meter_id);
    return meter ? meter.id : null;
};

// 创建区域
const createArea = async (name) => {
    try {
        await areaStore.createArea({ name: name });
        return areaStore.areas.find(a => a.name === name);
    } catch (error) {
        console.error(`创建区域失败: ${error}`);
        return null;
    }
};

// 获取或创建父表（重构版本）
const getOrCreateParentMeter = async (parentMeterId, excelData, allMeterList) => {
    // 如果parentMeterId不是纯数字，直接返回null
    if (!/^\d+$/.test(parentMeterId)) {
        console.log(`父表 ${parentMeterId} 不是纯数字，跳过创建`);
        return null;
    }

    // 先检查父表是否存在
    let parentId = getMeterIdByMeterId(allMeterList, parentMeterId);
    if (parentId) {
        console.log(`找到已存在的父表: ${parentMeterId}, ID: ${parentId}`);
        return parentId;
    }

    // 父表不存在，需要创建
    console.log(`父表 ${parentMeterId} 不存在，正在创建...`);

    // 从Excel数据中查找父表信息
    let parentData = excelData.find(item => item.meter_id === parentMeterId);
    if (!parentData) {
        console.error(`在Excel中未找到父表 ${parentMeterId} 的信息`);
        return null;
    }

    try {
        // 先处理父表的父表（递归）
        let grandParentId = null;
        if (parentData.parent_meter_id && parentData.parent_meter_id !== '0') {
            // 重新获取最新的表计列表（包含刚创建的表计）
            const latestMeterList = await getAllMeters();
            grandParentId = await getOrCreateParentMeter(
                parentData.parent_meter_id,
                excelData,
                latestMeterList
            );
        }

        // 处理父表的区域
        let area_id = null;
        if (parentData.area_name && parentData.area_name !== "总表" && parentData.area_name !== "虚拟") {
            let area = areaStore.areas.find(a => a.name === parentData.area_name);
            if (!area) {
                area = await createArea(parentData.area_name);
            }
            if (area) {
                area_id = area.id;
            }
        }

        const parentMeterInfo = {
            company_id: companyStore.currentCompany.id,
            meter_id: parentData.meter_id,
            meter_code: parentData.meter_code,
            type: parentData.type === "水表" ? 1 : 2,
            specification: parentData.specification,
            installation_location: parentData.installation_location,
            area_id: area_id,
            parent_id: grandParentId || 0, // 一级表计parent_id设为0
            engine_id: parentData.engine_id,
            manufacturer: parentData.manufacturer,
            installation_date: dayjs(importSettings.value.installation_date).format("YYYY-MM-DDTHH:mm:ss.SSSZ"),
            status: 1,
            is_drain_considerd: true,
            multiple: 1,
            bottom_value: 0,
            check_no_record: true,
            standard_coal_factor: 1,
        };

        const response = await addMeterApi(parentMeterInfo);
        console.log(`成功创建父表: ${parentMeterId}`);

        return response && response.id ? response.id : null;
    } catch (error) {
        console.error(`创建父表失败: ${parentMeterId}`, error);
        return null;
    }
};

// 文件处理方法
const handleFileChange = (file) => {
    const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
    if (!isExcel) {
        ElMessage.error('只能上传Excel文件!');
        return false;
    }

    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        ElMessage.error('上传文件大小不能超过 2MB!');
        return false;
    }

    parseExcelFile(file.raw);
    return true;
};

const beforeRemove = () => {
    previewData.value = [];
    return true;
};

const parseExcelFile = (file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
        try {
            const workbook = XLSX.read(e.target.result, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet);

            // 解析数据并格式化预览
            const parsed = parseExcelData(jsonData);
            previewData.value = parsed;

            ElMessage.success(`成功解析 ${parsed.length} 条表计数据`);
        } catch (error) {
            console.error('解析Excel文件失败:', error);
            ElMessage.error('解析Excel文件失败，请检查文件格式');
        }
    };
    reader.readAsBinaryString(file);
};

const parseExcelData = (data) => {
    const parsedData = [];

    for (let row of data) {
        if (row['__EMPTY_1'] === "表号") continue; // 跳过标题行

        // 判断引擎类型
        let engine_id = importSettings.value.engine_id;
        let manufacturer = importSettings.value.manufacturer;
        let engine_type = manufacturer;

        if (row['__EMPTY_5'] && row['__EMPTY_5'].toString() === 'PC5-B5Y') {
            engine_id = 5;
            manufacturer = '迈硕';
            engine_type = '迈硕';
        } else if (row['__EMPTY_4']) {
            engine_id = 16;
            manufacturer = '信驰机器人';
            engine_type = '信驰机器人';
        } else if (
            /[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ\-]/.test(row['__EMPTY_1']) &&
            !row['__EMPTY_4']
        ) {
            engine_id = 1;
            manufacturer = '虚拟表';
            engine_type = '虚拟表';
        }

        // 获取表号
        let meter_id = (engine_id === 16 && row['__EMPTY_4']) ? row['__EMPTY_4'].toString() : row['__EMPTY_1'].toString();

        const meterInfo = {
            type: row['__EMPTY'] || '水表',
            meter_id: meter_id,
            installation_location: row['__EMPTY_2'] || '',
            meter_code: row['__EMPTY_3'] ? row['__EMPTY_3'].toString() : '',
            specification: row['__EMPTY_5'] ? row['__EMPTY_5'].toString() : '',
            parent_meter_id: row['__EMPTY_8'] ? row['__EMPTY_8'].toString() : '',
            area_name: row['__EMPTY_9'] || '',
            engine_id: engine_id,
            manufacturer: manufacturer,
            engine_type: engine_type,
            // 原始数据，用于后续处理
            _raw: row
        };

        parsedData.push(meterInfo);
    }

    return parsedData;
};

// 重构后的startImport函数
const startImport = async () => {
    if (previewData.value.length === 0) {
        ElMessage.warning('请先上传并解析Excel文件');
        return;
    }

    importProgress.value = {
        visible: true,
        percentage: 0,
        status: '',
        text: '开始导入...'
    };

    try {
        const totalCount = previewData.value.length;
        let successCount = 0;
        let failCount = 0;

        // 获取所有表计（不通过Store，避免类型限制）
        let allMeterList = await getAllMeters();
        await areaStore.fetchAreas();

        console.log(`获取到 ${allMeterList.length} 个表计`);
        console.log('所有表计号:', allMeterList.map(m => m.meter_id));
        console.log('预览数据中的所有表号:', previewData.value.map(item => item.meter_id));
        console.log('预览数据中的所有父表号:', previewData.value.map(item => item.parent_meter_id).filter(Boolean));

        for (let i = 0; i < previewData.value.length; i++) {
            const row = previewData.value[i];

            try {
                // 更新进度
                const percentage = Math.round((i / totalCount) * 100);
                importProgress.value.percentage = percentage;
                importProgress.value.text = `正在导入第 ${i + 1} 条，表号: ${row.meter_id}`;

                // 处理父表关系
                let parent_id = 0; // 默认为0（一级表计）
                if (row.parent_meter_id && row.parent_meter_id !== '0') {
                    // 每次处理前都获取最新的表计列表
                    allMeterList = await getAllMeters();

                    // 先检查父表是否已存在
                    parent_id = getMeterIdByMeterId(allMeterList, row.parent_meter_id);

                    if (!parent_id) {
                        // 父表不存在，尝试创建
                        parent_id = await getOrCreateParentMeter(
                            row.parent_meter_id,
                            previewData.value,
                            allMeterList
                        );
                    }

                    // 如果还是找不到，设为0（一级表计）
                    if (!parent_id) {
                        console.log(`无法找到或创建父表 ${row.parent_meter_id}，设为一级表计`);
                        parent_id = 0;
                    } else {
                        console.log(`找到父表: ${row.parent_meter_id}, ID: ${parent_id}`);
                    }
                }

                // 处理区域
                let area_id = null;
                if (row.area_name && row.area_name !== "总表" && row.area_name !== "虚拟") {
                    let area = areaStore.areas.find(a => a.name === row.area_name);
                    if (!area) {
                        area = await createArea(row.area_name);
                    }
                    if (area) {
                        area_id = area.id;
                    }
                }

                const meterInfo = {
                    company_id: companyStore.currentCompany.id,
                    meter_id: row.meter_id,
                    meter_code: row.meter_code,
                    type: row.type === "水表" ? 1 : 2,
                    specification: row.specification,
                    installation_location: row.installation_location,
                    area_id: area_id,
                    parent_id: parent_id, // 使用0而不是null作为一级表计的标识
                    engine_id: row.engine_id,
                    manufacturer: row.manufacturer,
                    installation_date: dayjs(importSettings.value.installation_date).format("YYYY-MM-DDTHH:mm:ss.SSSZ"),
                    status: 1,
                    is_drain_considerd: true,
                    multiple: 1,
                    bottom_value: 0,
                    check_no_record: true,
                    standard_coal_factor: 1,
                };

                await addMeterApi(meterInfo);
                successCount++;
                console.log(`成功添加表计: ${row.meter_id}`);

            } catch (error) {
                failCount++;
                console.error(`处理表计失败: ${row.meter_id}`, error);

                // 如果是重复表计，不算作失败
                if (error.response && error.response.data && error.response.data.code === '23505') {
                    console.log(`表计已存在，跳过: ${row.meter_id}`);
                    successCount++;
                    failCount--;
                }
            }

            // 添加延迟避免请求过快
            await new Promise(resolve => setTimeout(resolve, 100));
        }

        // 完成导入
        importProgress.value.percentage = 100;
        importProgress.value.status = successCount === totalCount ? 'success' : 'warning';
        importProgress.value.text = `导入完成！成功: ${successCount}, 失败: ${failCount}`;

        // 通知父组件刷新
        emit('success', { successCount, failCount, totalCount });

        setTimeout(() => {
            importProgress.value.visible = false;
            handleClose();
        }, 2000);

    } catch (error) {
        importProgress.value.status = 'exception';
        importProgress.value.text = '导入过程中发生错误';
        console.error('批量导入失败:', error);
        ElMessage.error('批量导入失败');
    }
};

const handleClose = () => {
    previewData.value = [];
    uploadRef.value?.clearFiles();
    importProgress.value.visible = false;
    dialogVisible.value = false;
};
</script>

<style scoped>
.batch-import-container {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}

.import-settings {
    background-color: #f5f7fa;
    padding: 1rem;
    border-radius: 4px;
}

.import-settings h4 {
    margin: 0 0 1rem 0;
    color: #606266;
}

.settings-form .form-item-row {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
}

.file-upload-section h4 {
    margin: 0 0 1rem 0;
    color: #606266;
}

.format-help {
    margin-top: 1rem;
    padding: 1rem;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.format-help h5 {
    margin: 0 0 0.5rem 0;
    color: #606266;
    font-size: 14px;
}

.preview-section {
    background-color: #f5f7fa;
    padding: 1rem;
    border-radius: 4px;
}

.preview-section h4 {
    margin: 0 0 1rem 0;
    color: #606266;
}

.preview-info {
    margin-top: 1rem;
    padding: 0.5rem;
    background-color: #e6f7ff;
    border-radius: 4px;
    color: #1890ff;
    font-size: 14px;
}

.import-progress {
    background-color: #f5f7fa;
    padding: 1rem;
    border-radius: 4px;
}

.import-progress h4 {
    margin: 0 0 1rem 0;
    color: #606266;
}

.progress-text {
    margin-top: 0.5rem;
    text-align: center;
    color: #606266;
    font-size: 14px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 0.5rem;
}

.upload-demo {
    width: 100%;
}

.el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 7px;
}
</style>